<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Read Folder Images</title>
</head>

<body>
<input type="file" id="fileInput" webkitdirectory directory multiple/>
<script>
    async function readFileAsByteArray(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onloadend = function () {
                if (reader.result) {
                    resolve(new Uint8Array(reader.result));
                } else {
                    reject(new Error('读取文件字节流失败'));
                }
            };
            reader.onerror = function () {
                reject(reader.error);
            };
            reader.readAsArrayBuffer(file);
        });
    }

    document.getElementById('fileInput').addEventListener('change', function (e) {
        const fileList = e.target.files;
        const rootTreeNode = {
            parentName: null,
            name: "总单",
            type: "folder",
            fileByte: null,
            children: []
        };
        buildImageTree(fileList, rootTreeNode).catch(err => console.error(err));
        const imageTreeJson = JSON.stringify(rootTreeNode);
        console.log(imageTreeJson);
        // 这里可以将imageTreeJson发送给后端或者进行其他处理
    });

    async function buildImageTree(files, folderTreeNode) {
        for (const file of files) {
            if (file.name.endsWith('/')) {
                const subFolderTreeNode = {
                    parentName: folderTreeNode.name,
                    name: file.name.slice(0, -1),
                    type: "folder",
                    fileByte: null,
                    children: []
                };
                const subFiles = Array.from(file.entry.files || []);
                await buildImageTree(subFiles, subFolderTreeNode);
                folderTreeNode.children.push(subFolderTreeNode);
            } else {
                const fileExtension = file.name.split('.').pop().toLowerCase();
                const isImage = ['jpg', 'png', 'gif', 'jpeg'].includes(fileExtension);
                if (isImage) {
                    const fileTreeNode = {
                        parentName: folderTreeNode.name,
                        name: file.name,
                        type: "file",
                        fileByte: await readFileAsByteArray(file),
                        children: []
                    };
                    folderTreeNode.children.push(fileTreeNode);
                }
            }
        }
        return folderTreeNode;
    }
</script>
</body>

</html>